package com.kk.springboot_002.service.impl;

import com.kk.springboot_002.mapper.UserMapper;
import com.kk.springboot_002.pojo.User;
import com.kk.springboot_002.pojo.dto.RegisterDto;
import com.kk.springboot_002.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    @Override
    public User findByUserName(String username) {
        User user = userMapper.findByUserName(username);
        return user;
    }

    /**
     * 保存用户
     * @param user
     */
    @Override
    public void save(User user) {
        userMapper.save(user);
    }

    /**
     * 更新用户
     *
     * @param username
     * @param updateDto
     */
    @Override
    public void updateUser(String username, RegisterDto updateDto) throws Exception {
        //  1. 根据当前登录用户名，从数据库中获取用户信息
        User user = userMapper.findByUserName(username);
        if (user == null){
            throw new Exception("用户不存在");
        }
        // 2. 如果新用户名与旧用户名不同，则检查新用户名是否已存在
        if (updateDto.getName() != null && !updateDto.getName().equals(username)){
            User newUser = userMapper.findByUserName(updateDto.getName());
            if (newUser != null){
                throw new Exception("用户名已存在");
            }
            user.setName(updateDto.getName());
        }
        // 3. 如果密码字段不为空，则更新密码
        if (updateDto.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(updateDto.getPassword()));
        }
        // 4. 如果邮箱字段不为空，则更新邮箱
        if (updateDto.getEmail() != null) {
            user.setEmail(updateDto.getEmail());
        }
        // 5. 将更新后的实体保存到数据库
        userMapper.update(user);
    }

    /**
     * 删除用户
     * 需要注解Transactional，保证两步操作是原子性的
     * @param username
     * @return
     */
    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @Override
    @Transactional
    public boolean deleteUser(String username) {
        User user = userMapper.findByUserName(username);
        if (user != null){
            userMapper.deleteFruitsByUserId(user.getId());
            userMapper.deleteByUsername(username);
            log.info("删除用户成功：{}", username);
            return true;
        }
        return false;
    }
}
